package com.genericdevice.platform.core.event;

import com.genericdevice.platform.core.event.listeners.IEventListener;

import java.util.*;

/**
 * Created by Xilent on 17.05.2014.
 */
public class EventBus {
    private static Map<String, List<IEventListener>> LISTENERS = new HashMap<String, List<IEventListener>>();

    public static void addListener(String eventName, IEventListener listener) {
        List<IEventListener> listeners = LISTENERS.get(eventName);
        if (listeners == null) {
            listeners = new ArrayList<IEventListener>();
            LISTENERS.put(eventName, listeners);
        }

        listeners.add(listener);
    }

    public static void fireEvent(String eventName) {
        fireEvent(eventName, new DefaultEvent());
    }

    public static void fireEvent(String eventName, IEvent event) {
        List<IEventListener> listeners = LISTENERS.get(eventName);
        if (listeners == null)
            return;

        event.setName(eventName);

        Iterator<IEventListener> iterator = listeners.iterator();
        while (iterator.hasNext()) {
            IEventListener listener = iterator.next();

            if (listener.isOnce())
                iterator.remove();

            listener.onSuccess(event);
        }
    }

    public static void removeEventListeners(String name) {
        LISTENERS.remove(name);
    }

    public static void failEvent(String eventName) {
        failEvent(eventName, null);
    }

    public static void failEvent(String eventName, Throwable reason) {
        List<IEventListener> listeners = LISTENERS.get(eventName);
        if (listeners == null)
            return;

        Iterator<IEventListener> iterator = listeners.iterator();
        while (iterator.hasNext()) {
            IEventListener listener = iterator.next();

            if (listener.isOnce())
                iterator.remove();

            listener.onFailure(reason);
        }
    }
}
